package com.rytong.tools.ui.jsfunction;
//#define Android2.2
import android.R.string;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
//#ifdef Android2.2
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Email;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.CommonDataKinds.StructuredName;
import android.provider.ContactsContract.CommonDataKinds.StructuredPostal;
import android.provider.ContactsContract.Contacts.Data;
import android.provider.ContactsContract.PhoneLookup;
import android.provider.ContactsContract.RawContacts;
//#endif
import com.rytong.tools.ui.LPWebView.MyLPWebView;
import com.rytong.tools.utils.Utils;

public class EmpContact {
    final String UNKNOWN_ERROR = "1";
    final String OPEN_FAIL_ERROR = "2";
    final String ADD_FAIL_ERROR = "3";
    final String DEL_FAIL_ERROR = "4";

    /**
     * 打开通讯录
     * 
     * @param callback
     */
    public void open(Activity activity, MyLPWebView ewv, String callback) {
      //#ifdef Android2.2
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setData(Uri.parse("content://contacts/people"));
        Utils.getActivity().startActivity(intent);

        ContentResolver cr = activity.getContentResolver();
        // 取得电话本中开始一项的光标
        Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
        String name = "";
        String contactId = "";
        String phoneNumber = "";
        String email = "";
        String emailTemp;
        Cursor temp = null;
        String strPhoneNumber;
        String firstName = "";
        String middleName = "";
        String lastName = "";
        String address = "";
        // 生成js persion对象

        String arrayString = "var addressbook = new Array();";
        int index = 0;
        while (cursor.moveToNext()) {
            // 取得联系人ID
            contactId = "";
            contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));

            /**
             * 取得family_name和given_name
             */
            temp = cr.query(ContactsContract.Data.CONTENT_URI, new String[] { Data.RAW_CONTACT_ID,
                    StructuredName.DISPLAY_NAME, StructuredName.FAMILY_NAME, StructuredName.GIVEN_NAME,
                    StructuredName.MIDDLE_NAME }, ContactsContract.Data.CONTACT_ID + "=?" + " AND "
                    + ContactsContract.Data.MIMETYPE + "='"
                    + ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE + "'",
                    new String[] { contactId }, null);
            if (temp.moveToFirst()) {
                firstName = temp.getString(temp
                        .getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME));
                middleName = temp.getString(temp
                        .getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.MIDDLE_NAME));
                lastName = temp.getString(temp
                        .getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME));
            }

            // 取得联系人名字
            int nameFieldColumnIndex = cursor.getColumnIndex(PhoneLookup.DISPLAY_NAME);
            name = "";
            name = cursor.getString(nameFieldColumnIndex);

            temp = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                    ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contactId, null, null);
            strPhoneNumber = "";
            // 取得电话号码(可能存在多个号码)
            while (temp.moveToNext()) {
                strPhoneNumber = temp.getString(temp.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                phoneNumber = phoneNumber.concat(strPhoneNumber).concat(";");
            }
            // 取得邮箱地址
            temp = activity.getContentResolver().query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, null,
                    ContactsContract.CommonDataKinds.Email.CONTACT_ID + "=" + contactId, null, null);
            int emailIndex = 0;
            if (temp.getCount() > 0) {
                emailIndex = temp.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA);
            }
            while (temp.moveToNext()) {
                emailTemp = temp.getString(emailIndex);
                email = email.concat(emailTemp).concat(";");
            }
            // 取得地址
            temp = activity.getContentResolver().query(ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_URI,
                    null, ContactsContract.CommonDataKinds.StructuredPostal.CONTACT_ID + "=" + contactId, null, null);
            address = temp.getString(temp.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.STREET));
            // 将js person对象植入js 数组
            arrayString = arrayString.concat(" addressbook[").concat(String.valueOf(index)).concat("] = new Persion (")
                    .concat(firstName).concat(", ").concat(middleName).concat(", ").concat(lastName).concat(", ")
                    .concat(phoneNumber).concat(", ").concat(email).concat(", ").concat(address).concat("); ");
        }
        ewv.loadUrl("javascript:".concat(arrayString).concat(callback).concat("(addressbook);"));
        if (null != temp)
            temp.close();

        cursor.close();
      //#endif
    }

    /**
     * 向通讯录添加一个联系人
     * 
     * @param email
     * @param phoneNum
     * @param name
     */
    public long add(String firstname, String middlename, String lasetname, String phoneNum, String email, String address) {
     // #ifdef Android2.2
        ContentValues values = new ContentValues();
        Uri rawContactUri = Utils.getActivity().getContentResolver().insert(RawContacts.CONTENT_URI, values);
        long rawContactId = ContentUris.parseId(rawContactUri);

        values.clear();
        values.put(Data.RAW_CONTACT_ID, rawContactId);
        values.put(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE);
        values.put(StructuredName.GIVEN_NAME, firstname);
        Utils.getActivity().getContentResolver().insert(android.provider.ContactsContract.Data.CONTENT_URI, values);

        values.clear();
        values.put(Data.RAW_CONTACT_ID, rawContactId);
        values.put(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE);
        values.put(StructuredName.MIDDLE_NAME, middlename);
        Utils.getActivity().getContentResolver().insert(android.provider.ContactsContract.Data.CONTENT_URI, values);

        values.clear();
        values.put(Data.RAW_CONTACT_ID, rawContactId);
        values.put(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE);
        values.put(StructuredName.FAMILY_NAME, lasetname);
        Utils.getActivity().getContentResolver().insert(android.provider.ContactsContract.Data.CONTENT_URI, values);

        values.clear();
        values.put(Data.RAW_CONTACT_ID, rawContactId);
        values.put(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE);
        values.put(Phone.NUMBER, phoneNum);
        values.put(Phone.TYPE, Phone.TYPE_MOBILE);
        Utils.getActivity().getContentResolver().insert(android.provider.ContactsContract.Data.CONTENT_URI, values);

        values.clear();
        values.put(Data.RAW_CONTACT_ID, rawContactId);
        values.put(Data.MIMETYPE, Email.CONTENT_ITEM_TYPE);
        values.put(Email.DATA, email);
        values.put(Email.TYPE, Email.TYPE_WORK);
        Utils.getActivity().getContentResolver().insert(android.provider.ContactsContract.Data.CONTENT_URI, values);
        values.clear();

        values.clear();
        values.put(Data.RAW_CONTACT_ID, rawContactId);
        values.put(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE);
        values.put(StructuredPostal.STREET, address);
        Utils.getActivity().getContentResolver().insert(android.provider.ContactsContract.Data.CONTENT_URI, values);

        return rawContactId;
        // #else
//@        return 0;
     // #endif
    }

    public void delete(Activity activity, String first, String middle, String last, String phoneNum, String email,
            String address) {
        // #ifdef Android2.2
        Uri uri = Uri.parse("content://com.android.contacts/raw_contacts");
        ContentResolver resolver = activity.getContentResolver();
        Cursor cursor = resolver.query(uri, new String[] { Data._ID }, "display_name=?",
                new String[] { first.concat(middle).concat(last) }, null);
        int id = 0;
        if (cursor.moveToFirst()) {
            id = cursor.getInt(0);
            // 根据id删除data中的相应数据
        }
        if (null != first && !first.equals("") && null != middle && !middle.equals("") && null != last
                && !last.equals("") && null != phoneNum && !phoneNum.equals("") && null != address
                && !address.equals("")) {
            // 删除整条记录,该注销方法为另一种删除方法
            // ContentResolver cr = activity.getContentResolver();
            // Cursor contactsCur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
            // while (contactsCur.moveToNext()) {
            // // 获取ID
            // String rawId = contactsCur.getString(contactsCur.getColumnIndex(ContactsContract.Contacts._ID));
            // // 删除
            // String where = ContactsContract.Data._ID + " =?";
            // String[] whereparams = new String[] { rawId };
            // activity.getContentResolver().delete(ContactsContract.RawContacts.CONTENT_URI, where, whereparams);
            // }

            if (cursor.moveToFirst()) {
                id = cursor.getInt(0);
                // 根据id删除data中的相应数据
                // resolver.delete(uri, "display_name=?", new String[] { name });
                uri = Uri.parse("content://com.android.contacts/data");
                resolver.delete(uri, "raw_contact_id=?", new String[] { id + "" });
            }

            // 一边查找，一边删除，<把通讯录里的联系人都删除了>
        } else {
            // 删除记录中的若干项
            ContentValues values = new ContentValues();
            if (null != first) {
                values.put(StructuredName.GIVEN_NAME, first);
                Utils.getActivity()
                        .getContentResolver()
                        .delete(android.provider.ContactsContract.Data.CONTENT_URI, " raw_contact_id=? and mimetype=?",
                                new String[] { id + "", StructuredName.CONTENT_ITEM_TYPE });
                values.clear();
            }
            if (null != middle) {
                values.put(StructuredName.MIDDLE_NAME, middle);
                Utils.getActivity()
                        .getContentResolver()
                        .delete(android.provider.ContactsContract.Data.CONTENT_URI, " raw_contact_id=? and mimetype=?",
                                new String[] { id + "", StructuredName.CONTENT_ITEM_TYPE });
                values.clear();
            }
            if (null != last) {
                values.put(StructuredName.FAMILY_NAME, last);
                Utils.getActivity()
                        .getContentResolver()
                        .delete(android.provider.ContactsContract.Data.CONTENT_URI, " raw_contact_id=? and mimetype=?",
                                new String[] { id + "", StructuredName.CONTENT_ITEM_TYPE });
                values.clear();
            }
            if (null != phoneNum) {
                values.put(Phone.NUMBER, phoneNum);
                Utils.getActivity()
                        .getContentResolver()
                        .delete(android.provider.ContactsContract.Data.CONTENT_URI,
                                " raw_contact_id=? and mimetype=? and data2=?",
                                new String[] { id + "", Phone.CONTENT_ITEM_TYPE, "2" });

                values.clear();
            }
            if (null != email) {
                values.put(Email.DATA, email);
                Utils.getActivity()
                        .getContentResolver()
                        .delete(android.provider.ContactsContract.Data.CONTENT_URI,
                                " raw_contact_id=? and mimetype=? and data2=?",
                                new String[] { id + "", Email.CONTENT_ITEM_TYPE, "2" });
                values.clear();
            }
            if (null != address) {
                values.put(StructuredPostal.STREET, address);
                Utils.getActivity()
                        .getContentResolver()
                        .delete(android.provider.ContactsContract.Data.CONTENT_URI,
                                " raw_contact_id=? and mimetype=? and data2=?",
                                new String[] { id + "", Email.CONTENT_ITEM_TYPE, "2" });
                values.clear();
            }
        }
        // #endif
    }
    
}
